import { get } from '../../common/conf'
import { createClient } from 'redis'

let client = null

const runRedis = async () => {
  const url = get('db.redis')
  client = createClient({ url })
  client.on('error', (err) => console.log('Redis Client Error ', err))
  client.on('ready', () => console.log('Redis Client Ready'))
  client.on('reconnecting', () => console.log('Redis Client Re Connect'))
  await client.connect()
  setValue('ST_INFO', {
    stamp: Date.now(),
    time: new Date().toISOString(),
    url
  })
  // await client.set('start time', new Date().toUTCString())
  // const st = await client.get('start time')
}

const getClient = () => {
  return client
}

// 存储值
const setValue = (key, value, ex = -1) => {
  let exOpts = {}
  if (ex && ex > 0) {
    exOpts = {
      EX: ex,
      NX: true
    }
  }
  const type = typeof value
  console.log(`redis T[${type}] V[${JSON.stringify(value)}] EX[${ex}]`)
  if (type === 'string' || type === 'number') {
    client.set(key, value, exOpts)
  } else if (type === 'object') {
    for (const item in value) {
      client.hSet(key, item, value[item])
    }
  }
}

// 数值自增
const incrValue = (key, value) => {
  client.incr(key, value)
}

// 获取string
const getValue = (key) => {
  return new Promise((resolve, reject) => {
    client.get(key, (err, res) => {
      if (err) {
        reject(err)
      } else {
        resolve(res)
      }
    })
  })
}

// 获取hash
const getHVals = (key) => {
  return new Promise((resolve, reject) => {
    client.hGetAll(key, function (err, value) {
      if (err) {
        reject(err)
      } else {
        resolve(value)
      }
    })
  })
}

const getHAll = (key) => {
  return new Promise((resolve, reject) => {
    client.hVals(key, function (err, value) {
      if (err) {
        reject(err)
      } else {
        resolve(value)
      }
    })
  })
}

export default {
  setValue,
  incrValue,
  getValue,
  getHAll,
  getHVals,
  client,
  runRedis,
  getClient
}
